
#[cfg(test)]
mod test {
    use std::{thread, panic};
    use std::thread::{Builder, current};
    use std::cell::RefCell;
    use std::time::Duration;

    #[test]
    fn test_thread() {
        let mut v = vec![];
        for id in 0..5 {
            let child = thread::spawn(move || {
                println!("in child: {}", id);
            });
            v.push(child);
        }
        println!("in main: join before ");
        for child in v {
            child.join();
        }
        println!("in main: join after");
    }

    // 定制线程
    #[test]
    fn test_thread_specify() {
        let mut v = vec![];
        for id in 0..5 {
            let thread_name = format!("child-{}", id);
            let size: usize = 3 * 1024;
            let builder = Builder::new().name(thread_name).stack_size(size);
            let child = builder.spawn(move || {
                println!("in child: {}", id);
                if id == 3 {
                    panic::catch_unwind(|| {
                        panic!("oh no!");
                    });
                    // 使用 thread::current() 函数来获取当前线程
                    println!("in {} do sm", current().name().unwrap());
                }
            }).unwrap();
            v.push(child);
        }

        for child in v {
            child.join().unwrap();
        }
    }

    #[test]
    fn test_thread_local() {
        thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
        FOO.with(|f| {
            assert_eq!(*f.borrow(), 1);
            *f.borrow_mut() = 2;
        });

        thread::spawn(|| {
            FOO.with(|f| {
                assert_eq!(*f.borrow(), 1);
                *f.borrow_mut() = 3;
            });
        });

        FOO.with(|f| {
            assert_eq!(*f.borrow(), 2);
        });
    }

    #[test]
    fn test_thread_park() {
        let parked_thread = thread::Builder::new()
            .spawn(|| {
                println!("Parking thread");
                thread::park();
                println!("Thread unparked");
            }).unwrap();

        thread::sleep(Duration::from_millis(2000));
        println!("Unpark the thread");
        parked_thread.thread().unpark();
        parked_thread.join().unwrap();
    }
}